package com.baimo.support.log;

import com.google.gson.Gson;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.CodeSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Component
@Aspect
@Order(-1)
public class LogAspect {

    private static Logger log = LoggerFactory.getLogger(LogAspect.class);

    @Before("within(com.baimo.support.*.controller.*)")
    public void before(JoinPoint joinPoint){
        Gson gson = new Gson();
        try {
            // 接收到请求，记录请求内容
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            StringBuffer logStr = new StringBuffer();
            HttpServletRequest request = attributes.getRequest();
            // 记录下请求内容
            logStr.append("request for:" + request.getRequestURI());
            logStr.append("   parameter:");
            // joinPoint获取参数名
            String[] params = ((CodeSignature) joinPoint.getStaticPart().getSignature()).getParameterNames();
            // joinPoint获取参数值
            Object[] args = joinPoint.getArgs();

            // 打印请求参数
            if(args!=null && args.length==0) {
                logStr.append(" {} ");
            }else {
                int i = 0;
                for (Object arg : args) {
                    if (arg!=null && arg.equals(request)) {
                        i+=1;
                        continue;
                    }
                    logStr.append("&"+params[i]+"="+ gson.toJson(arg));
                    i+=1;
                }
            }
            log.info(logStr.toString());
        } catch (Throwable e) {
            log.error("aspect request param error.", e);
        }



    }
}
